import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:second_hand/data/shared_preferences_service.dart';
import 'package:second_hand/pages/welcome.dart';
import '../../data/admin_data.dart';

class AdminView extends GetView<AdminController> {

  const AdminView({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(AdminController());
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品审核'),
        actions: [
          IconButton(
            icon: const Icon(Icons.logout),
            onPressed: _logout,
          ),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: RefreshIndicator(
              onRefresh: () => controller.loadPage(controller.currentPage.value),
              child: Obx(() => ListView.builder(
                itemCount: controller.items.length,
                itemBuilder: (context, index) =>
                    _buildItemCard(controller.items[index]),
              )),
            ),
          ),
          _buildPaginationBar(),
        ],
      ),
    );
  }

  Widget _buildItemCard(dynamic item) {
    return Card(
      margin: const EdgeInsets.all(8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (item['image'] != null && item['image'].isNotEmpty)
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.network(
                  item['image'],
                  height: 150,
                  width: double.infinity,
                  fit: BoxFit.cover,
                  errorBuilder: (_, __, ___) => Container(
                    height: 150,
                    color: Colors.grey[200],
                    child: const Icon(Icons.broken_image),
                  ),
                ),
              ),
            const SizedBox(height: 12),
            Text('商品名称：${item['name']}',
                style: const TextStyle(fontSize: 16)),
            const SizedBox(height: 6),
            Text('价格：¥${(item['price'] as num).toStringAsFixed(2)}',
                style: TextStyle(color: Get.theme.primaryColor)),
            const SizedBox(height: 6),
            Text('校区：${(item['campuses'] as List).join(', ')}'),
            const SizedBox(height: 6),
            Text('创建时间：${item['create_time']}',
                style: const TextStyle(color: Colors.grey, fontSize: 12)),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                OutlinedButton.icon(
                  icon: const Icon(Icons.check, size: 18),
                  label: const Text('通过'),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.green,
                    side: const BorderSide(color: Colors.green),
                  ),
                  onPressed: () =>
                      controller.handleReview(item['id'], true),
                ),
                const SizedBox(width: 10),
                OutlinedButton.icon(
                  icon: const Icon(Icons.close, size: 18),
                  label: const Text('拒绝'),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: Colors.red,
                    side: const BorderSide(color: Colors.red),
                  ),
                  onPressed: () =>
                      controller.handleReview(item['id'], false),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPaginationBar() {
    return Obx(() => Container(
      padding: const EdgeInsets.symmetric(vertical: 8),
      color: Colors.grey[100],
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          IconButton(
            icon: const Icon(Icons.chevron_left),
            onPressed: controller.currentPage.value > 1
                ? controller.previousPage
                : null,
          ),
          Text(
            '第 ${controller.currentPage} 页 / 共 ${controller.totalPages} 页',
            style: const TextStyle(fontSize: 16),
          ),
          IconButton(
            icon: const Icon(Icons.chevron_right),
            onPressed: controller.currentPage.value <
                controller.totalPages.value
                ? controller.nextPage
                : null,
          ),
        ],
      ),
    ));
  }
  void _logout() {
    Get.defaultDialog(
      title: "请确认",
      middleText: '  是否确认退出登录？',
      backgroundColor: Colors.white,
      actions: [
        TextButton(
          onPressed: () {
            Get.back(); // 关闭对话框
          },
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () async {
            await SharedPreferencesService.clearAdminToken();
            await SharedPreferencesService.clearToken();
            Get.offAll(() => WelcomePage());
            Get.snackbar("退出成功","", duration: const Duration(seconds: 1));
          },
          child: const Text('确认'),
        ),
      ],
    );
  }
}